﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml.Linq;

namespace Dqaqs.Web.Common
{
	public class JsonHelper
	{
		public static JsonResult Error(string errorText)
		{
			return new JsonResult {Data = new {Error = errorText}, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
		}

		public static object PrepareSchemaForJson(string schema)
		{
			var el = XElement.Parse(schema);
			var tables = el.Elements("Table").Select(l => new
															{
																table = l.Attribute("Name").Safe(a => a.Value),
																columns =
															l.Elements("Column").
															Select(cl => new
															             	{
															             		name = cl.Attribute("Name").Safe(a => a.Value),
																				iskey = (bool)((bool?)cl.Attribute("IsKey") ?? false),
																				type = (string)cl.Attribute("Type")
															             	} ).ToList()
															}).ToList();
			return tables;
		}

		public static string GenerateSchemaFromJson(string json)
		{
			ArgumentCheck.IsNotNull(json, "json");
			var jss = new JavaScriptSerializer();
			var sch = (Dictionary<string, object>)jss.DeserializeObject(json);
			var sb = new StringBuilder();
			sb.Append("<Tables>");
			foreach (var tbl in (object[])sch["Tables"])
			{
				var tblObj = (Dictionary<string, object>) tbl;
				sb.AppendFormat("<Table Name=\"{0}\">", tblObj["Name"]);
				var cols = tblObj["Columns"] as object[];
				if (cols != null)
				{
					foreach (var col in cols)
					{
						var colObj = (Dictionary<string, object>) col;
						sb.AppendFormat("<Column Name=\"{0}\" IsKey=\"{1}\" Type=\"{2}\" />", 
							colObj["Name"], ((string)colObj["IsKey"]).Equals("true", StringComparison.InvariantCultureIgnoreCase) 
								? true : false, colObj["Type"]);
					}
				}
				sb.Append("</Table>");
			}
			sb.Append("</Tables>");
			return sb.ToString();
		}
	}
}